<?php

namespace App\Repository;

use App\Entity\LogType;
use App\Utils\Enum\RedisKeyEnum;
use App\Service\RedisService;
use App\Utils\Traits\FilterTrait;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @method LogType|null find($id, $lockMode = null, $lockVersion = null)
 * @method LogType|null findOneBy(array $criteria, array $orderBy = null)
 * @method LogType[]    findAll()
 * @method LogType[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class LogTypeRepository extends ServiceEntityRepository {
    use FilterTrait;

    private $redis;

    public function __construct (ManagerRegistry $registry, RedisService $redis) {
        parent::__construct($registry, LogType::class);
        $this->redis = $redis->redis;
    }

    public function findAllToArray () {
        $result = [];

        $redis_key = RedisKeyEnum::REDIS_LOG_TYPE_FIND_ALL_BY_ARRAY_KEY;
        $redis_log_type_data = $this->redis->get($redis_key);
        if (is_null($redis_log_type_data)) {
            $objs = $this->findAll();
            foreach ($objs as $obj) {
                $result[$obj->getId()] = $obj->getValue();
            }
            $this->redis->setex($redis_key, 600, serialize($result));
        } else {
            $result = unserialize($redis_log_type_data);
        }

        return $result;
    }

    /**
     * @return array|int|string
     */
    public function getArrayResult () {
        return $this->createQueryBuilder('l')
            ->getQuery()
            ->getArrayResult();
    }
}
